{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 生成token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import base64\n",
    "import json\n",
    "import time\n",
    "from Crypto.PublicKey import RSA\n",
    "from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKC\n",
    "\n",
    "class HandleRSA():\n",
    "    # Server使用Client的公钥对内容进行rsa 加密\n",
    "    def encrypt(self, plain_text, public_pem):\n",
    "        \"\"\"\n",
    "        plain_text: 需要加密的明文文本\n",
    "        public_pem: 公钥\n",
    "        \"\"\"\n",
    "        # 加载公钥\n",
    "        rsa_key = RSA.import_key(public_pem)\n",
    "        # 加密\n",
    "        cipher_rsa = Cipher_PKC.new(rsa_key)\n",
    "        en_data = cipher_rsa.encrypt(plain_text.encode(\"utf-8\"))  # 加密\n",
    "        # base64 进行编码\n",
    "        return base64.b64encode(en_data).decode()\n",
    "\n",
    "def generate_encrypt(data, public_pem):\n",
    "    \"\"\"\n",
    "    生成encrypt\n",
    "    \"\"\"\n",
    "    mrsa = HandleRSA()\n",
    "    encrypt = mrsa.encrypt(data, public_pem)\n",
    "    return encrypt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "import hashlib\n",
    "\n",
    "def md5(input_string):\n",
    "    # 创建md5对象\n",
    "    md5_hash = hashlib.md5()\n",
    "    \n",
    "    # 需要确保输入的是字节串，因此对字符串进行编码\n",
    "    md5_hash.update(input_string.encode('utf-8'))\n",
    "    \n",
    "    # 返回MD5哈希值的十六进制表示\n",
    "    return md5_hash.hexdigest()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "public_pem = \"\"\"-----BEGIN RSA PUBLIC KEY-----\n",
    "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDBTEBurFuIRIwxBT7R8EkBdsvl\n",
    "L3GTjP1E4V/QpLaMklWsjpNbKWyycx3LT/QeTeYwM08Pp/LcOSyTS9a4L9oY9DPe\n",
    "knwme0yCWJZDfbPnUTvbEuiJdXQVWFYZx/Eh3F7gMhUeBPAmEQ5E+r7PypvdsIzP\n",
    "uiiATpVH41ccEDNS4QIDAQAB\n",
    "-----END RSA PUBLIC KEY-----\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "将参数键值对列表按下标进行排序:  [('expire', 3600), ('external_uid', 1233), ('tid', [24126, 24126, 24126, 24126, 24126, 24126, 24126, 24126, 24126, 12345678]), ('username', '绑定的用户')]\n",
      "参数转成json字符串并去除空格:  [[\"expire\",3600],[\"external_uid\",1233],[\"tid\",[24126,24126,24126,24126,24126,24126,24126,24126,24126,12345678]],[\"username\",\"\\u7ed1\\u5b9a\\u7684\\u7528\\u6237\"]]\n",
      "将参数字符串转成md5字符串:  6fb40d32d8ddf724c0d248141b1a1c7c\n",
      "加密参数字符串:  nT2th68ugrBTsgODWqLgNytzInhEoTbbHc6GXm5+ZXTUI7TOp0jF0SV101WoisDI/3cn62nmldILsTidou4xyCAG5eIWuzBmtpNDz6n6bd3arWbsxIffrn7aYsUbzSF7DSPXwgf0n+MyMgG5wB1rtU+WyWLa/N/AUihnsIeqbkY=\n"
     ]
    }
   ],
   "source": [
    "# 原始参数\n",
    "en_params = {\n",
    "    \"username\": \"绑定的用户\",           # 对应抽取系统的用户名，该用户在抽取系统已经开启公钥私钥登陆\n",
    "    \"expire\": 3600,                    # token有效期，单位：秒\n",
    "    \"external_uid\": 1233,              # 在第三方系统的用户ID，可以为空（里面是int类型，例：\"1\",\"2\",\"\"，不要为：\"null\", \"None\"）\n",
    "    \"tid\": [24126, 24126, 24126, 24126, 24126, 24126, 24126, 24126, 24126, 12345678],            # 指定抽取任务ID，可以批量（int类型，如果不需要应该不加入此字段）\n",
    "}\n",
    "\n",
    "params_list = sorted(en_params.items())\n",
    "print(\"将参数键值对列表按下标进行排序: \", params_list)\n",
    "\n",
    "params_str = json.dumps(params_list)\n",
    "params_str = params_str.replace(\" \", \"\")\n",
    "print(\"参数转成json字符串并去除空格: \", params_str)\n",
    "\n",
    "params_md5 = md5(params_str)\n",
    "print(\"将参数字符串转成md5字符串: \", params_md5)\n",
    "\n",
    "encrypted_text = generate_encrypt(params_md5, public_pem)\n",
    "print(\"加密参数字符串: \", encrypted_text)\n",
    "\n",
    "# 组成最后的参数\n",
    "en_params[\"encrypt\"] = encrypted_text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.10.11 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "c7af7df4901773a0e355da496bf365ae011b1b331a57bbc9908dae1ee21823d7"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
